<template>
  <div>
    <!--表格栏-->
    <el-table :data="data.content" :highlight-current-row="highlightCurrentRow" @selection-change="selectionChange" @cell-click="rowclick"
          @current-change="handleCurrentChange" v-loading="loading" :element-loading-text="$t('action.loading')" :border="border" :stripe="stripe"
          :show-overflow-tooltip="showOverflowTooltip" :max-height="maxHeight" :size="size" :align="align" style="width:100%;" >
      <el-table-column type="selection" width="40" v-if="showBatchDelete & showOperation"></el-table-column>
          <el-table-column type="index" label="序号" width="50">
    </el-table-column>
      <el-table-column v-for="column in columns" header-align="center" align="center"
        :prop="column.prop" :label="column.label" :width="column.width" :min-width="column.minWidth"
        :fixed="column.fixed" :key="column.prop" :type="column.type" :formatter="column.formatter"
        :sortable="column.sortable==null?true:column.sortable">
      </el-table-column>
      <el-table-column :label="$t('action.operation')" width="300" fixed="right" v-if="showOperation" header-align="center" align="center">
        <template slot-scope="scope">
          <kt-button icon="fa fa-edit" :label="$t('action.edit')" :perms="permsEdit" :size="size" @click="handleEdit(scope.$index, scope.row)" />
          <kt-button icon="fa fa-trash" :label="$t('action.delete')" :perms="permsDelete" :size="size" type="danger" @click="handleDelete(scope.$index, scope.row)" />
          <kt-button icon="fa fa-trash" label="开始" :perms="permsStart" :size="size" type="primary" @click="handleStart(scope.$index, scope.row)"  v-if="showItemB=='showItemB' && scope.row.status==1" />
          <kt-button icon="fa fa-trash" label="结束" :perms="permsEnd" :size="size" type="primary" @click="handleEnd(scope.$index, scope.row)"  v-if="showItemB=='showItemB' && scope.row.status==2"/>
          <!-- <kt-button icon="fa fa-trash" label="查看" :perms="permsLook" :size="size" type="primary" @click="handleLook(scope.$index, scope.row)"  v-if="showItemView"/> -->
          <kt-button icon="fa fa-trash" label="发布" :perms="permsRelease" :size="size" type="primary" @click="handleRelease(scope.$index, scope.row)"  v-if="showItemView && scope.row.status == 1" />
          <kt-button icon="fa fa-trash" label="下架" :perms="permsOffline" :size="size" type="primary" @click="handleOffline(scope.$index, scope.row)"  v-if="showItemView  && scope.row.status == 2"/>

        </template>
      </el-table-column>
    </el-table>
    <!--分页栏-->
    <div class="toolbar" style="padding:10px;">
      <kt-button :label="$t('action.batchDelete')" :perms="permsDelete" :size="size" type="danger" @click="handleBatchDelete()"
        :disabled="this.selections.length===0" style="float:left;" v-if="showBatchDelete & showOperation"/>
				<kt-button :label="$t('action.start')" :perms="permsAuditStart" type="primary" :disabled="this.selections.length===0" style="float:left;" @click="handleAuditStart"  v-if="showAuditB"/>
				<kt-button :label="userrType=='student'?'提交':'审核'" :perms="permsAudit" type="primary" :disabled="this.selections.length===0" style="float:left;" @click="handleAudit" v-if="showAuditB"/>
        <kt-button :label="$t('action.uploadFile')" :perms="permsUploadFile" type="primary" :disabled="this.selections.length!==1" style="float:left;" @click="handleUpload" v-if="showAuditB"/>
        <kt-button :label="$t('action.tail')" :perms="permsView" type="primary" :disabled="this.selections.length!==1" style="float:left;" @click="handleView" v-if="showAuditB"/>
      <el-pagination layout="total, prev, pager, next, jumper" @current-change="refreshPageRequest"
        :current-page="pageRequest.pageNum" :page-size="pageRequest.pageSize" :total="data.totalSize" style="float:right;">
      </el-pagination>
    </div>
          <!-- 附件弹框-->
       <el-dialog
      class="login-resetPwd"
      title="上传附件"
      :visible.sync="uploadDialogVisible"
      width="30%"
      s>
      <el-input v-model="fileName" placeholder="请输入内容"></el-input>
          <el-upload
            style="display: inline-block;margin: 0 10px"
            action="string"
            :show-file-list="false"
            :http-request="uploadFileImport"
            :before-upload="beforeFirstAvatarUpFile"
            title="导入"
          >
            <el-button type="primary" class="tableBtn">选择文件</el-button>
          </el-upload>
           <el-button type="primary" @click="uploadFile">上传</el-button>
           <el-table
            :data="tableData"
            style="width: 100%">
            <el-table-column
              prop="name"
              label="文件名称"
              width="180">
            </el-table-column>
            <el-table-column
              label="操作">
          <template slot-scope="scope">
          <kt-button icon="fa fa-edit" :label="$t('action.download')" :size="size"  @click="handleDownload(scope.$index, scope.row)" />
          <kt-button icon="fa fa-trash" :label="$t('action.delete')"  :size="size" type="danger" @click="handleRemove(scope.$index, scope.row)" />
        </template>
            </el-table-column>
          </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button @click="uploadDialogVisible = false">取 消</el-button>
    </span>
  </el-dialog>

            <!-- 审核弹框-->
       <el-dialog
      class="login-resetPwd"
      title="审核"
      :visible.sync="AuditDialogVisible"
      width="30%"
      s>
       <el-form :model="auditForm"  ref="auditForm" label-position="left" label-width="100px" class="demo-ruleForm login-container">

        <!-- <el-form-item label="审核人" prop="toOperationId"  >
         <el-select v-model="auditForm.toOperationId" placeholder="请选择"  style="width: 100%;">
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.nickName"
              :value="item.id">
            </el-option>
          </el-select>
			</el-form-item> -->
        <el-form-item label="审核意见" class="file-line" prop="desc">
          <el-input   type="textarea"
          placeholder="请输入内容"
          v-model="auditForm.desc"
          maxlength="30"
          show-word-limit ></el-input>
        </el-form-item>

  </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleSubmit">{{buttonName}}</el-button>
      <el-button @click="handleBack" v-if="userrType != 'student'">驳回</el-button>
      <el-button @click="AuditDialogVisible = false">取消</el-button>
    </span>
  </el-dialog>

              <!-- 时间线弹框-->
       <el-dialog
      class="login-resetPwd"
      title="审核记录"
      :visible.sync="ViewDialogVisible"
      width="30%"
      s>
       <el-timeline>
    <el-timeline-item
      v-for="(activity, index) in activities"
      :key="index"
      :color="activity.status == 1 ? '#0bbd87':''"
      :icon="activity.status == 1 ? 'el-icon-loading':''"
      :timestamp="activity.createTime">
        <el-card>
        <h4> 当前节点由：{{activity.operationUser}} {{activity.operationName}}</h4>
        <p v-if="activity.operationType != 1">审批意见： {{activity.desc}}</p>
        <p v-if="activity.operationType != 4">下一审批人： {{activity.toOperationUser}}</p>
      </el-card>
    </el-timeline-item>
  </el-timeline>
    <span slot="footer" class="dialog-footer">
      <el-button @click="ViewDialogVisible = false">确认</el-button>
      <el-button @click="ViewDialogVisible = false">取消</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>
import KtButton from "@/views/Core/KtButton"
export default {
  name: 'KtTable',
  components:{
			KtButton
	},
  props: {
    columns: Array, // 表格列配置
    data: Object, // 表格分页数据
    permsEdit: String,  // 编辑权限标识
    permsDelete: String,  // 删除权限标识
    permsStart: String,  // 权限标识
    permsEnd: String,  // 权限标识
    permsLook: String,  // 权限标识
    permsRelease: String,  // 权限标识
    permsOffline: String,  // 权限标识
    permsAuditStart: String,  // 权限标识
    permsAudit: String,  // 权限标识
    permsUploadFile: String,  // 权限标识
    permsView: String,  // 权限标识
    size: { // 尺寸样式
      type: String,
      default: 'mini'
    },
    align: {  // 文本对齐方式
      type: String,
      default: 'left'
    },
    maxHeight: {  // 表格最大高度
      type: Number,
      default: 440
    },
    showOperation: {  // 是否显示操作组件
      type: Boolean,
      default: true
    },
    border: {  // 是否显示边框
      type: Boolean,
      default: false
    },
    stripe: {  // 是否显示斑马线
      type: Boolean,
      default: true
    },
    highlightCurrentRow: {  // // 是否高亮当前行
      type: Boolean,
      default: true
    },
    showOverflowTooltip: {  // 是否单行显示
      type: Boolean,
      default: true
    },
    showBatchDelete: {  // 是否显示操作组件
      type: Boolean,
      default: true
    },
    showItemB: {  // 是否显示操作组件
      type: String,
      default:''
    },
    showAuditB:{
      type: Boolean,
      default: false
    },
    pageType:{
      type: Number,
      default: 0
    },
    showItemView:{
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 分页信息
			pageRequest: {
				pageNum: 1,
        pageSize: 9
      },
      loading: false,  // 加载标识
      selections: [] , // 列表选中列
      uploadDialogVisible: false, //上传文件弹框
      tableData:[], //附件列表
      itemFile:{},
      fileName:'',
      AuditDialogVisible:false,
      userOptions:[],
      auditForm:{
        toOperationId: null,
        desc: ''
      },
      ViewDialogVisible:false,
      buttonName:"通过",
      userrType:'',
      activities:[],
    }
  },
  methods: {
    // 分页查询
    findPage: function () {
        this.loading = true
        let callback = res => {
          this.loading = false
        }
      this.$emit('findPage', {pageRequest:this.pageRequest, callback:callback})
    },
    // 选择切换
    selectionChange: function (selections) {
      this.selections = selections
      this.$emit('selectionChange', {selections:selections})
    },

    // 选择切换
    handleCurrentChange: function (val) {
      this.$emit('handleCurrentChange', {val:val})
    },
    // 换页刷新
		refreshPageRequest: function (pageNum) {
      this.pageRequest.pageNum = pageNum
      this.findPage()
    },
    // 编辑
		handleEdit: function (index, row) {
      this.$emit('handleEdit', {index:index, row:row})
		},
        // 查看
		handleLook: function (index, row) {
      this.$emit('handleLook', {index:index, row:row})
		},

        // 选择切换
    rowclick: function (row, column, event) {
      if(column.property == 'title'){
       this.$emit('handleLook', {column:column, row:row})
      }
    },
            // 发布
		handleRelease: function (index, row) {
      	this.release(row.id)
		},
            // 下架
		handleOffline: function (index, row) {
      	this.offline(row.id)
		},

    // 删除
		handleDelete: function (index, row) {
      if(this.showItemView && row.status == 2){
        this.$message({message: '操作失败, 请先下架公告在进行删除' , type: 'error'})
        return
      }else{
        this.delete(row.id)
      }


		},
		// 批量删除
		handleBatchDelete: function () {
     let ids = this.selections.map(item => item.id).toString()
      if(this.showItemView){
        this.selections.forEach(element => {
          this.$message({message: '操作失败, 请先下架公告在进行删除' , type: 'error'})
          return
        });
      }else{
         this.delete(ids)
      }


		},
    handleStart: function (index, row) {
			this.start(row.id)
		},
    handleEnd: function (index, row) {
			this.end(row.id)
		},
    handleUpload(){
         let fileParams = {
            type:this.pageType,
            busiId:this.selections[0].id
          }
          this.findFiles(fileParams)
        this.fileName = ''
          this.uploadDialogVisible = true


    },
		// 删除操作
		delete: function (ids) {
			this.$confirm('确认删除选中记录吗？', '提示', {
				type: 'warning'
			}).then(() => {
				let params = []
				let idArray = (ids+'').split(',')
				for(var i=0; i<idArray.length; i++) {
					params.push({'id':idArray[i]})
        }
        this.loading = true
        let callback = res => {
          if(res.code == 200) {
            this.$message({message: '删除成功', type: 'success'})
            this.findPage()
          } else {
            this.$message({message: '操作失败, ' + res.msg, type: 'error'})
          }
          this.loading = false
        }
        this.$emit('handleDelete', {params:params, callback:callback})
			}).catch(() => {
			})
		},
      		// 开启学期填报
		start: function (id) {
			this.$confirm('确认开启选中的学期综测填报吗？', '提示', {
				type: 'warning'
			}).then(() => {
        this.loading = true
        let callback = res => {
          if(res.code == 200) {
            this.$message({message: '开启成功', type: 'success'})
            this.findPage()
          } else {
            this.$message({message: '操作失败, ' + res.msg, type: 'error'})
          }
          this.loading = false
        }
        this.$emit('handleStart', {params:id, callback:callback})
			}).catch(() => {
			})
  },
  		// 结束学期填报
		end: function (id) {
			this.$confirm('确认结束选中的学期综测填报吗？', '提示', {
				type: 'warning'
			}).then(() => {
        this.loading = true
        let callback = res => {
          if(res.code == 200) {
            this.$message({message: '删除成功', type: 'success'})
            this.findPage()
          } else {
            this.$message({message: '操作失败, ' + res.msg, type: 'error'})
          }
          this.loading = false
        }
        this.$emit('handleEnd', {params:id, callback:callback})
			}).catch(() => {
			})
    },

          		//发布公告
		release: function (id) {
			this.$confirm('确认发布所选中的公告吗？', '提示', {
				type: 'warning'
			}).then(() => {
        this.loading = true
        let callback = res => {
          if(res.code == 200) {
            this.$message({message: '发布成功', type: 'success'})
            this.findPage()
          } else {
            this.$message({message: '操作失败, ' + res.msg, type: 'error'})
          }
          this.loading = false
        }
        this.$emit('handleRelease', {params:id, callback:callback})
			}).catch(() => {
			})
  },

          		// 下线公告
		offline: function (id) {
			this.$confirm('确认发布所选中的公告吗？', '提示', {
				type: 'warning'
			}).then(() => {
        this.loading = true
        let callback = res => {
          if(res.code == 200) {
            this.$message({message: '下架成功', type: 'success'})
            this.findPage()
          } else {
            this.$message({message: '操作失败, ' + res.msg, type: 'error'})
          }
          this.loading = false
        }
        this.$emit('handleOffline', {params:id, callback:callback})
			}).catch(() => {
			})
  },
    uploadFile(){
          if(this.selections[0].status == 1 || this.selections[0].status == 2){
              let formData = new FormData()
              formData.append('file', this.itemFile)
              formData.append('type', this.pageType)
              formData.append('busiId', this.selections[0].id)
              let fileParams = {
                type:this.pageType,
                busiId:this.selections[0].id
              }
              this.$api.sysFile.save(formData).then(res => {
                  this.findFiles(fileParams)
              })

          }else{
              this.$message.error('请选择待提交的数据上传')
         }

    },
    findFiles(fileParams){
      this.$api.sysFile.findList(fileParams).then(res =>{
          this.tableData = res.data
      })
    },
    uploadFileImport(item){
      this.itemFile = item.file
    },
    beforeFirstAvatarUpFile(file){
      this.fileName = file.name
    },
    handleAuditStart(){

      let isEvery = this.selections.every((item) =>{
          return item.status == 1
      })
      if(!isEvery){
           this.$message.error("请选择正确的数据进行提交")
           return
      }
     //this.AuditDialogVisible = true
      this.handleSubmit()
    },
    handleAudit(){
      this.$api.user.findByName({name:sessionStorage.getItem('user')}).then(res =>{
        this.userrType = res.data.type
      })
      let isEvery = this.selections.every((item) =>{
          if(item.status == 1 || item.status == 6){
            return false
          }
          if(this.userrType == 'classAdmin'){
              return (item.status == 4 || item.status == 3 )
          }else if(this.userrType == 'collegeAdmin'){
              return (item.status == 5 )
          }else if(this.userrType == 'admin'){
              return (item.status == 2 || item.status == 3  || item.status == 4 || item.status == 5 )
          }else{
             return item.status == 2
          }
      })
      if(!isEvery){
           this.$message.error("请选择正确的数据进行审核")
           return
      }
     this.AuditDialogVisible = true
    },
    handleDownload(index, row){
          this.$api.sysFile.download(row).then(data => {
          //let fileName = data.headers['content-disposition'].slice(data.headers['content-disposition'].indexOf('=') + 1)
          let fileName = row.name
          //let type = data.headers[`content-type`].slice(0, data.headers[`content-type`].indexOf(';'))
          let blob = new Blob([data])
          if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a')
            elink.setAttribute('download', decodeURI(fileName))
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放 URL对象
            document.body.removeChild(elink)
          } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
    })
    },
    handleRemove(index, row){
          if(this.selections[0].status == 1 || this.selections[0].status == 2){
            let fileParams = {
              type:this.pageType,
              busiId:this.selections[0].id
            }
            this.$api.sysFile.remove(row).then(res =>{
              this.findFiles(fileParams)
            })

          }else{
              this.$message.error('请选择待提交的数据删除')
         }

    },
    handleView(){
      this.$api.busFlow.findList({busiId:this.selections[0].id,type:this.pageType}).then(res =>{
          if(res.code == 200){
            this.activities = res.data
            this.ViewDialogVisible = true
          }else{
             this.$message({message: '查询失败, ' + res.msg, type: 'error'})
          }
      })

    },
    getParams(){
      let params = []
      this.selections.forEach(element => {
        params.push({
          id:element.id,
          status:element.status,
          studentNum:element.studentNum,
        })
      });
      return params
    },
    handleSubmit(){
      let data = {
        type: this.pageType,
        list: this.getParams(),
        //toOperationId: this.auditForm.toOperationId,
        desc: this.auditForm.desc
      }
      this.$api.busFlow.audit(data).then(res =>{
        if(res.code == 200) {
            this.$message({message: '操作成功', type: 'success'})
            this.findPage(null)
            this.AuditDialogVisible = false
          } else {
            this.$message({message: '操作失败, ' + res.msg, type: 'error'})
          }

      })
    },
    handleBack(){
      let data = {
        type: this.pageType,
        list: this.getParams(),
        toOperationId: this.auditForm.toOperationId,
        desc: this.auditForm.desc
      }
      this.$api.busFlow.back(data).then(res =>{
        if(res.code == 200) {
            this.$message({message: '操作成功', type: 'success'})
            this.findPage(null)
            this.AuditDialogVisible = false
          } else {
            this.$message({message: '操作失败, ' + res.msg, type: 'error'})
          }

      })
    },
    getButtonName(){
      this.$api.user.findByName({name:sessionStorage.getItem('user')}).then(res =>{
        if(res.data.type == 'collegeAdmin'){
           this.buttonName = "完成"
        }else if(res.data.type == 'classAdmin'){
           this.buttonName = "通过"
        }else if(res.data.type == 'student' || res.data.type == 'teacher'){
           this.buttonName = "提交"
        }
      })
    },
    getUserOption(){
        this.$api.user.findAuditOptions().then(res =>{
          this.userOptions = res.data
        })
    }
  },

  mounted() {
    this.refreshPageRequest(1)
    this.getButtonName()
   // this.getUserOption()
    this.$api.user.findByName({name:sessionStorage.getItem('user')}).then(res =>{
        this.userrType = res.data.type
    })
  }

}
</script>

<style scoped>

</style>
